'use strict'
const path = require('path')
const pkgDir = require('pkg-dir').sync
const formatPath = require('@wjp-cli-dev/format-path')
const { getDefaultRegistry, getNpmLatestVersion } = require('@wjp-cli-dev/get-npm-info')
const npminstall = require('npminstall')
const pathExists = require('path-exists').sync
class Package {
  constructor(option) {
    console.log(option)
    if (!option) {
      throw new Error('package类的option参数不能为空')
    }
    this.targetPath = option.targetPath
    // 缓存package的路径
    this.storeDir = option.storePath
    this.homePath = option.homePath
    this.packageName = option.packageName
    this.packageVersion = option.packageVersion

    // package的缓存目录前缀
    this.cacheFilePathPrefix = this.packageName.replace('/', '_')
  }

  get cacheFilePath () {
    return `${this.cacheFilePathPrefix}@${packageVersion}@${this.packageName}`
  }

  async prepare () {
    if (this.storeDir && !pathExists(this.storeDir)) {
      fse.mkdirpSync(this.storeDir)
    }
    if (this.packageVersion === 'latest') {
      this.packageVersion = await getNpmLatestVersion(this.packageName)
    }
  }

  // 判断当前Package是否存在
  async exists () {
    await this.prepare()
    if (this.storeDir) {
      console.log(this.cacheFilePath)
      // await this.prepare();
      console.log('storeDir', pathExists(this.cacheFilePath))
      return pathExists(this.storeDir)
    } else {
      console.log('targetPath', pathExists(this.targetPath))
      return pathExists(this.targetPath)
    }
  }

  // 安装package
  install () {
    const root = path.resolve(this.homePath, '.imooc-wjp')
    console.log(root, getDefaultRegistry())
    npminstall({
      root: this.targetPath,
      // storeDir: root + 'node_modules',
      storeDir: this.storeDir,
      registry: getDefaultRegistry(),
      pkgs: [
        { name: 'foo', version: '1.0.0' }
      ]
    })
  }

  // 更新package
  update () {

  }

  // 获取入口文件的路径
  getRootFilePath () {
    // 1.获取package.json所在目录
    const dirPath = pkgDir(this.targetPath)
    // console.log('getRootFilePath', dirPath)
    if (dirPath) {
      // 2.读取package.json
      const pkgFile = require(path.resolve(dirPath, 'package.json'))
      // 3.寻找main/lib
      if (pkgFile && pkgFile.main) {
        // 4.路径兼容（macOs， windows）
        const entryPath = formatPath(path.resolve(dirPath, pkgFile.main))
        console.log('getRootFilePath', entryPath)
        return entryPath
      }

    }
  }

}

module.exports = Package
